package com.javawork.juc.threadLocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 需求1：5个销售卖房子，集团只关心销售了多少套
 * 需求2：5个销售卖房子，各自独立销售额度，业绩按提成走，分灶吃饭
 * @author zhangxiaolu
 * @since 2023-02-13 22:05
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
//                System.out.println(size);
                try {
                    for (int j = 0; j <size; j++) {
                        house.saleHouse();
                        house.saleVolumeByThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName() + "号销售卖出：" + house.saleVolume.get());
                } finally {
                    house.saleVolume.remove();//防止线程泄露
                }
            }, String.valueOf(i)).start();
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("共卖出：" + house.saleCount);
    }
}

class House {

    int saleCount = 0;

    public synchronized void saleHouse() {
        ++saleCount;
    }

    /*ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/

    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);

    public void saleVolumeByThreadLocal() {
        saleVolume.set(1+saleVolume.get());
    }
}